package org.redmagic.service.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.redmagic.service.HierarchicalService;
import org.redmagic.service.domain.HierarchicalRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Stopwatch;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@RequestMapping("/bulk")
@Controller
public class BulkPropertyController {

	@Autowired
	private HierarchicalService service;

	@RequestMapping(value = "*")
	public @ResponseBody String retrieveProperties(HttpServletRequest request, @RequestBody String requestJson) {

		Stopwatch stopWatch = new Stopwatch().start();
		
		System.out.println("Bulk Property Request: " + requestJson);
		
		// convert the json request to a usable form
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		HierarchicalRequest hierarchicalRequest = gson.fromJson(requestJson, HierarchicalRequest.class);
		
		// get the requesting server
		String user = request.getRemoteHost();
		
		// get the response from the service
		Map<String, String> resolvedProperties = service.getHierarchicalProperties(hierarchicalRequest, user);
		String responseJson = gson.toJson(resolvedProperties);
		
		System.out.println("Bulk Property response: " + responseJson);		
		System.out.println("Bulk Request Total time: " + stopWatch.elapsedMillis() + " (ms)");
		
		return responseJson;
	}

	public HierarchicalService getService() {
		return service;
	}

	public void setService(HierarchicalService service) {
		this.service = service;
	}
}
